<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <title>测评者面板</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        /* 自定义样式，用于美化表格等展示效果 */
        table#contestTable {
            width: 100%;
            border-collapse: collapse;
        }

        table#contestTable th,
        table#contestTable td {
            border: 1px solid #ccc;
            padding: 8px;
            text-align: left;
        }

        table#contestTable th {
            background-color: #f2f2f2;
        }

        button.btn-sm {
            margin-right: 5px;
        }
		
		.form-label {
			font-size: 20px;
			background-color: #f2f2f2;
			font-family: "楷体", serif;
			font-weight: bold;
		}
    </style>
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">测评者面板</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
                    aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link" data-bs-toggle="pill" href="#homeSection">首页</a>
                    </li>
                </ul>
            </div>
            <div class="navbar-nav ms-auto">
                <div class="dropdown">
                    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton"
                            data-bs-toggle="dropdown" aria-expanded="false">
                        欢迎您<span id="userNameSpan"></span> <!-- 新增一个span用于显示用户名 -->	
                    </button>
                    <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                        <li><a class="dropdown-item" href="#" id="logoutBtn">退出登录</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </nav>
    <div class="container mt-5">
        <div class="tab-content">
            <!-- 首页功能区域 -->
            <div class="tab-pane fade show active" id="homeSection">
                <h2>首页</h2>
                <p>欢迎来到测评者面板首页，这里可以进行相关测评操作。</p>
                <div id="questionForms"></div>
            </div>
        </div>
    </div>
	
	<script>
	// 加载当前比赛ID的函数，用于刷新显示当前比赛ID，假设后端接口为 /loadCurrentContestId，根据实际调整
		function loadCurrentContestId() {
			$.ajax({
					type: "GET",
					url: "/getCurrentContestId",
					dataType: "json",
					success: function (response) {
						console.log(response)
						var questionFormsDiv = $('#questionForms');
                        questionFormsDiv.empty();
                        for (var i = 0; i < response.questions.length; i++) {
                            var question = response.questions[i];
                            var qname = "题目名称: " + question.question_name;
                            var form = '<form id="questionForm_' + i + '" class="mb-3">\
                                            <label class="form-label"> ' + qname + '</label>\
                                            <input type="file" id="uploadFile_' + i + '" class="form-control " accept=".cpp">\
                                            <button type="button" class="btn btn-primary submit-btn" data-question-id="' + i + '">提交</button>\
											<span id="uploadStatus_' + i + '">未上传</span>\
                                        </form>';
                            questionFormsDiv.append(form);
                        }
					},
					error: function (xhr, status, error) {
						console.error('获取当前比赛ID出现错误：', xhr, status, error);
						const currentContestIdElement = document.getElementById('currentContestId');
						currentContestIdElement.textContent = '获取当前比赛ID出现错误，请稍后再试';
					}
				});
		}
		// 为文件输入框添加点击事件处理，点击后设置对应状态为"未上传"
		$(document).on('click', '[id^="uploadFile_"]', function () {
			var questionId = $(this).attr('id').replace('uploadFile_', '');
			var uploadStatusSpan = $('#uploadStatus_' + questionId);
			uploadStatusSpan.text('未上传');
		});
		// 为每个题目表单的提交按钮添加点击事件处理
            $(document).on('click', '.submit-btn', function () {
                var questionId = $(this).data('question-id');
				var fileInput = $('#uploadFile_' + questionId)[0];
				// 先将状态重置为"未上传"
				var uploadStatusSpan = $('#uploadStatus_' + questionId);
				// uploadStatusSpan.text('未上传');
                if (fileInput.files.length > 0) {
                    var fileName = fileInput.files[0].name;
                    if (!fileName.toLowerCase().endsWith('.cpp')) {
                        alert('请选择.cpp文件进行上传');
                        return false;
                    }
                }
                // alert('你点击了题目 ' + (questionId + 1) + ' 的提交按钮，后续需完善提交相关逻辑');
                // 创建FormData对象来收集表单数据（这里主要是文件数据，后续可扩展添加其他表单元素数据）
                var formData = new FormData();
                if (fileInput.files.length > 0) {
                    formData.append('file', fileInput.files[0]);
                }
                // 添加题目相关的其他数据（示例中暂未体现其他数据，若有可按如下格式添加，比如题目编号等）
				// console.log(fileName.split('.')[0])
                formData.append('questionName', fileName.split('.')[0]);
				formData.append('username', "{{ username }}");

                // 发起POST请求上传文件和相关数据到后端（假设后端接口为/submit_answer，需根据实际调整）
                $.ajax({
                    type: "POST",
                    url: "/submit_answer",
                    data: formData,
                    contentType: false, // 注意设置，避免jQuery对FormData进行额外处理
                    processData: false, // 同上
                    success: function (response) {
                        alert('提交成功，后端返回信息：' + response.message);
						uploadStatusSpan.text('已上传');
                    },
                    error: function (xhr, status, error) {
                        console.error('提交答案出现错误:', xhr, status, error);
                        alert("提交答案出现错误，请稍后再试");
                    }
                });
            });

            // 添加样式应用逻辑，确保页面加载时样式能正确应用到题目表单上（如果需要动态添加样式的情况）
            $('form[id^="questionForm_"]').each(function () {
                $(this).css({
                    'display': 'flex',
                    'align-items': 'center',
                    'gap': '10px',
                    'border': '1px solid #ccc',
                    'border-radius': '5px',
                    'padding': '10px',
                    'box-shadow': '0 0 5px rgba(0, 0, 0, 0.1)'
                });
            });
		
		// 页面加载完成后加载比赛列表数据并展示
        $(document).ready(function () {
			loadCurrentContestId();
			
			// 获取当前登录账户名并显示在右上角（这里假设从localStorage中获取，根据实际情况调整）
			var currentUserName = "{{ username }}";
			console.log("账户名", currentUserName)
			if (!currentUserName) currentUserName = "没成功" 
			if (currentUserName) {
				$('#userNameSpan').text(' ' + currentUserName); // 在span中显示用户名，添加空格隔开文字
			}
		});
	</script>

	

    <script>
        $(document).ready(function () {
            // 点击退出登录按钮的事件处理
            $(document).on('click', '#logoutBtn', function (e) {
                e.preventDefault();
                $.ajax({
                    type: "POST",
                    url: "/logout",
                    dataType: "json",
                    success: function (response) {
                        if (response.success) {
                            // 成功退出登录后直接跳转到登录页面
                            window.location.href = "/";
                        } else {
                            alert(response.message);
                        }
                    },
                    error: function (xhr, status, error) {
                        // 记录错误日志以便调试
                        console.error('退出登录请求出现错误:', xhr, status, error);
                        // 给用户提供更友好的错误提示
                        alert("退出登录时发生错误，请检查网络连接或稍后重试。");
                    }
                });
            });
        });
    </script>
</body>

</html>